	<template>
		<view class="u-wrap u-p-l-20 u-p-r-20">
			<u-form :model="addModel" ref="form1" :rules="rules">
				<u-form-item label="名称:" prop="goodsName">
					<u-input placeholder="请输入名称" v-model="addModel.goodsName" />
				</u-form-item>
				<u-form-item label="分类:" prop="categoryName">
					<u-input placeholder="请选择分类" v-model="addModel.categoryName" @click="showCategory = true" />
					<u-select v-model="showCategory" :list="categoryList" @confirm="handleCategoryConfirm"></u-select>
				</u-form-item>
				<u-form-item label="简介:" prop="introduce">
					<u-input placeholder="请输入简介" v-model="addModel.introduce" />
				</u-form-item>
				<u-form-item label-width="auto" label="联系电话:" prop="phoneNum">
					<u-input placeholder="请输入联系电话" v-model="addModel.phoneNum" />
				</u-form-item>
				<u-form-item label-width="auto" label="微信号:" prop="wechatId">
					<u-input placeholder="请输入微信号" v-model="addModel.wechatId" />
				</u-form-item>
				<u-form-item label-width="auto" label="上传图片:" prop="image">
					<u-upload ref="imgUploadRef" :action="action" :file-list="fileList" @on-change="onChange"
						@on-remove="onRemove"></u-upload>
				</u-form-item>
				<u-form-item label="价格:" prop="price">
					<u-input placeholder="请输入价格" v-model="addModel.price" />
				</u-form-item>
				<u-form-item label="原价:" prop="originalPrice">
					<u-input placeholder="请输入原价" v-model="addModel.originalPrice" />
				</u-form-item>
			</u-form>

			<u-button :custom-style="customStyle" @click="publishCommit">发布</u-button>
		</view>
	</template>
	<script setup>
		import {
			reactive,
			ref
		} from 'vue';
		import {
			onReady
		} from "@dcloudio/uni-app"
		import http from '../../common/http/http.js'
		import {
			publish
		}
		from '../../api/goods.js'
		import {
			getSelectList
		} from '../../api/category.js'

		const addModel = reactive({
			userId: uni.getStorageSync('userId'),

			categoryId: 1,
			categoryName: '',
			goodsName: '',
			introduce: '',
			price: '',
			originalPrice: '',
			phoneNum: '',
			wechatId: '',
			image: '',

		})
		const imgUploadRef = ref()
		const form1 = ref()
		// 表单验证规则
		const rules = reactive({
			goodsName: [{
				required: true,
				message: '名称不能为空',
				trigger: 'blur'
			}],
			categoryName: [{
				required: true,
				message: '请选择分类',
				trigger: 'blur'
			}],
			introduce: [{
				required: true,
				message: '简介不能为空',
				trigger: ['change', 'blur']
			}],
			phoneNum: [{
				required: true,
				message: '联系电话不能为空',
				trigger: 'blur'
			}, {
				pattern: /^1[3-9]\d{9}$/,
				message: '请输入正确的手机号',
				trigger: 'blur'
			}],
			wechatId: [{
				required: true,
				message: '微信号不能为空',
				trigger: 'blur'
			}],
			image: [{
				required: true,
				message: '请上传图片',
				trigger: ['change', 'blur']
			}],
			/*trigger{String | Array}：触发校验的方式有2种： 	
	change：字段值发生变化时校验
	blur：输入框失去焦点时触发
	如果同时监听两种方式，需要写成数组形式：['change', 'blur']*/
			price: [{
					required: true,
					message: '价格不能为空',
					trigger: ['change', 'blur']
				},
				{
					pattern: /^\d+(\.\d{1,2})?$/,
					message: '请输入正确的价格格式',
					trigger: ['change', 'blur']
				}
			],

			originalPrice: [{
				required: true,
				message: '价格不能为空',
				trigger: 'blur'
			}, {
				pattern: /^\d+(\.\d{1,2})?$/,
				message: '请输入正确的价格格式',
				trigger: 'blur'
			}],
		});
		const showCategory = ref(false)
		const categoryList = ref([])
		const getSelectListData = async () => {
			const res = await getSelectList()
			if (res && res.code == 200) {
				// console.log(res.data)
				categoryList.value = res.data
			}

		}
		const handleCategoryConfirm = (selected) => {
			if (selected.length > 0) {
				addModel.categoryName = selected[0].label; // 更新分类名称
				addModel.categoryId = selected[0].value; // 更新分类ID
				// console.log("cate id", addModel.categoryId)
				// console.log("cate name", addModel.categoryName)
			}
			showCategory.value = false; // 关闭下拉框
		};
		const value = ref('')
		// action图片上传地址
		const action = ref(http.baseUrl + "/api/upload/image")
		// 使用空数组存储图片路径,然后用push存入
		const imageUrls = ref([])
		// 图片上传触发
		const onChange = (e) => {
			// console.log("onChange",e)
			// onChange {statusCode: 200, data: "{"msg":"upload success","code":200,"data":"/develop/image/f72ecdd8-b204-43e9-9a81-0703cca22361.png"}", header: {…}, cookies: Array(0), errMsg: "uploadFile:ok"}cookies: []data: "{"msg":"upload success","code":200,"data":"/develop/image/f72ecdd8-b204-43e9-9a81-0703cca22361.png"}"errMsg: "uploadFile:ok"header: {Content-Type: "application/json", Transfer-Encoding: "chunked", Date: "Mon, 17 Mar 2025 01:51:58 GMT", Keep-Alive: "timeout=60", Connection: "keep-alive"}statusCode: 200__proto__: Object
			// console.log(e.data.data)
			// undefined 直接访问 e.data.data 得不到结果，因为 e.data 是一个字符串，而不是对象。
			// console.log(e.data)
			// {"msg":"upload success","code":200,"data":"/develop/image/b69590b5-3e79-482e-a859-b0a716ab8a2b.png"}
			// 使用 JSON.parse() 将 JSON 格式的字符串转换为 JavaScript 对象后，才能访问其中的属性。
			let imgRes = JSON.parse(e.data)
			// console.log(imgRes.data)
			// /develop/image/50b12d56-814a-4762-ac53-21e464644136.png
			// 将图片路径存入数组
			// console.log(http.baseUrl)
			imageUrls.value.push(http.baseUrl + imgRes.data)
			// 把数组中的图片转换为逗号分隔的字符串
			// http://localhost:8089
			let url = ""
			for (let i = 0; i < imageUrls.value.length; i++) {
				url = url + imageUrls.value[i] + ","
			}
			// console.log(url)
			// http://localhost:8089/develop/image/afcddf95-c801-4c60-8f6a-f019b025b6e7.jpg,http://localhost:8089/develop/image/4d71931d-c24e-4680-bc70-0ced02e9000a.jpg,http://localhost:8089/develop/image/88ae2346-fa2c-45eb-b2b0-4766bfb4887a.jpg,
			// 去掉最后一个逗号
			addModel.image = url.substring(0, url.length - 1)
			console.log(addModel)
			// console.log(addModel.image)

		}
		// 图片移除
		const onRemove = (index) => {
			// console.log(index)
			imageUrls.value.splice(index, 1)
			let url = ""
			for (let i = 0; i < imageUrls.value.length; i++) {
				url = url + imageUrls.value[i] + ","
			}
			// 去掉最后一个逗号
			addModel.image = url.substring(0, url.length - 1)
			console.log(addModel)

		}
		// 发布提交
		const publishCommit = () => {
			console.log(addModel)
			form1.value.validate(async (valid) => {
				// console.log(valid)
				if (valid) {
					let result = await publish(addModel)
					console.log("API响应:", result) // 确保这里能输出

					if (result && result.code == 200) {
						console.log("发布成功", result)
						uni.showToast({
							title: '发布成功',
							icon: 'success',
							duration: 2000,
						});
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/index/index'
							}) // 延迟跳转确保Toast显示
						}, 500)
					}
					form1.value.resetFields() // 重置表单
					// 清空图片
					imageUrls.value = []
					addModel.image = ''
					fileList.value = []
					imgUploadRef.value.clear() // 清空上传组件
				}
			})
		}

		const fileList = ref([])
		const customStyle = reactive({
			// 按钮字体颜色
			color: '#ffffff',
			background: '#E30131',
			border: '1px solid #E30131',
			// 边距
			// margin:'50px',
			// 仅将元素的上外边距设置为 50 像素
			marginTop: '50px',
			width: '100%'
		})

		onReady(() => {
				// console.log('onReady')
				form1.value.setRules(rules)
				getSelectListData()
			}

		)
	</script>

	<style>

	</style>